package me.pppploi8.webmcs.main.filter;

import java.io.File;
import java.util.Calendar;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;

import me.pppploi8.webmcs.http.jetty.HttpFilter;
import me.pppploi8.webmcs.main.tools.Utils;
import me.pppploi8.webmcs.minecraft.server.core.McServerFactory;

public class WebmcsSaveLoginStatusFilter implements HttpFilter{
	private static long cacheTime = 0;
	private static String cacheUsername = null;
	private static long cacheMaxTime = 0;
	private static String cacheUUID = null;

	@Override
	public boolean handle(HttpServletRequest request, HttpServletResponse response) {
		String username = (String)request.getSession().getAttribute("username");
		if (Utils.stringIsBlank(username)){
			//未登录，继续检测cookie中的uuid和本地uuid记录是否相等
			Cookie[] cookies = request.getCookies();
			String uuid = null;
			for(Cookie cookie : cookies){
				if (cookie.getName().equals("uuid")){
					uuid = cookie.getValue();
					break;
				}
			}
			if (uuid != null){
				flushCookieCache(); 
				long currentDate = Calendar.getInstance().getTimeInMillis();
				if (uuid.equals(cacheUUID) && currentDate <= cacheMaxTime){
					request.getSession().setAttribute("username", cacheUsername);
				}
			}
		}
		return true;
	}

	private void flushCookieCache() {
		File file = new File(McServerFactory.getMcServerCore().getServerPath().getParent() + "/login.status");
		if (file.exists()){
			if(file.lastModified() > cacheTime){
				// 重新读取缓存文件内容
				try{
					String conf = FileUtils.readFileToString(file, "UTF-8");
					String[] arr = conf.split("\r\n");
					cacheUsername = arr[0];
					cacheMaxTime = Long.parseLong(arr[1]);
					cacheUUID = arr[2];
				}catch(Exception e){
					e.printStackTrace();
					cacheUsername = null;
					cacheMaxTime = 0;
					cacheUUID = null;
				}
			}
		}else{
			cacheUsername = null;
			cacheMaxTime = 0;
			cacheUUID = null;
		}
	}
}
